<?php

namespace App\Service\Admin;

use App\Model\Admin\MenuModel;
use App\Model\Admin\RoleMenuModel;
use App\Model\Admin\RoleModel;
use App\Service\BaseService;

/**
 * 系统角色管理-服务类
 * @author LZH
 * @since: 2021/08/12
 * Class RoleService
 */
class RoleService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new RoleModel();
        parent::__construct();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2021/08/12
     * @author LZH
     */
    public function getList()
    {
        $param = $this->getRequestParam();

        // 查询条件
        $map = [];


        return parent::getList($map);
    }

    /**
     * 获取角色列表
     * @return mixed
     * @author LZH
     */
    public function getRoleList()
    {
        $list = $this->model->where([
            'status' => 1,
            'mark' => 1
        ])->order("sort", "asc")
            ->all()
            ->toArray();
        return $list;
    }

    /**
     * 获取权限列表
     * @return array
     */
    public function getPermissionList()
    {
        // 角色ID
        $roleId = $this->getRequestParam("role_id") ?: 0;
        // 获取全部菜单
        $menuModel = new MenuModel();
        $menuList = $menuModel->getList([
            ['status' => [1]]
        ], ['sort' => 'asc']);
        if (!empty($menuList)) {
            $roleMenuModel = new RoleMenuModel();
            $roleMenuList = $roleMenuModel->getList([
                ['role_id' => [$roleId]]
            ]);
            $menuIdList = array_key_value($roleMenuList, "menu_id");
            foreach ($menuList as &$val) {
                if (in_array($val['id'], $menuIdList)) {
                    $val['checked'] = true;
                    $val['open'] = true;
                }
            }
        }
        return $menuList;
    }

    /**
     * 保存权限
     * @return array
     */
    public function savePermission()
    {
        // 角色ID
        $roleId = $this->getRequestParam("role_id") ?? 0;
        $roleMenuModel = new RoleMenuModel();
        $roleMenuModel->where("role_id", $roleId)->destroy();
        // 插入角色菜单关系数据
        $param = $this->getRequestParam();
        unset($param['role_id']);
        if (is_array($param) && !empty($param)) {
            $list = [];
            foreach ($param as $val) {
                $data = [
                    'role_id' => $roleId,
                    'menu_id' => $val,
                ];
                $list[] = $data;
            }
        }
        return array_keys($roleMenuModel->saveAll($list));
    }


}
